package com.common.file;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BOMInputStream;

import java.io.*;
import java.net.URL;
import java.nio.channels.FileChannel;

/**
 * description: FileTools <br>
 * date: 2022/12/23  <br>
 * author: zss <br>
 * version: 1.0.0 <br>
 */
public class FileTools {

    /**
     * 读取资源文件，不需要添加前缀
     * @param filename
     * @return
     */
    public static InputStream readResourcesFile(String filename){
        //读取到jar包里面的文件
        URL url = Thread.currentThread().getContextClassLoader().getResource(filename);
        try {
            byte[] body = IOUtils.toByteArray(url);
            InputStream inputStream = new ByteArrayInputStream(body);
            //处理bom格式文件
            BOMInputStream bomInputStream = new BOMInputStream(inputStream);
            return bomInputStream;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void transferTo(String fromFile, String toFile) throws IOException
    {
        File fileToCopy = new File(fromFile);
        FileInputStream inputStream = new FileInputStream(fileToCopy);
        FileChannel inChannel = inputStream.getChannel();

        File newFile = new File(toFile);
        FileOutputStream outputStream = new FileOutputStream(newFile);
        FileChannel outChannel = outputStream.getChannel();

        inChannel.transferTo(0, fileToCopy.length(), outChannel);

        inputStream.close();
        outputStream.close();
    }

}
